/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.exception.diagnostic.reporter;

import io.iec.edp.caf.commons.runtime.CafEnvironment;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.diagnostics.FailureAnalysis;
import org.springframework.boot.diagnostics.FailureAnalysisReporter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 根据异常分析结果进行异常报告
 * @author wangyandong
 * @date 2021/05/07 09:25
 *
 */
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class CAFFailureAnalysisReporter implements FailureAnalysisReporter {

    private static final Log logger = LogFactory.getLog(CAFFailureAnalysisReporter.class);

    @Override
    public void report(FailureAnalysis failureAnalysis) {
//        if (logger.isDebugEnabled()) {
//            logger.debug("应用启动失败，原因如下", failureAnalysis.getCause());
//        }
        String message = buildMessage(failureAnalysis);
        logger.error(message,failureAnalysis.getCause());

    }

    private String buildMessage(FailureAnalysis failureAnalysis) {
        StringBuilder builder = new StringBuilder();
        builder.append(String.format("%n"));
        builder.append(String.format("***************************%n"));
        builder.append(String.format("     系统启动失败%n"));
        builder.append(String.format("***************************%n%n"));
        builder.append(String.format("异常描述:%n%n"));
        builder.append(String.format(" %s%n", failureAnalysis.getDescription()));
        if (StringUtils.hasText(failureAnalysis.getAction())) {
            builder.append(String.format("%n解决方案:%n%n"));
            builder.append(String.format(" %s%n", failureAnalysis.getAction()));
        }
        return builder.toString();
    }

    private boolean isErrorEnabled(){
        Boolean enableConsoleLog = CafEnvironment.getEnvironment().getProperty("ENABLE_CONSOLE_LOGGING",Boolean.class,true);

        //如果禁止输出控制台日志，则直接输出一下
        return enableConsoleLog && logger.isErrorEnabled();
    }
}
